// sm4_decrypt.c
#include <stdio.h>
#include <stdlib.h>
#include <openssl/evp.h>
#include "utils.h"

int main(int argc, char *argv[]) {
    if (argc != 5) {
        fprintf(stderr, "Usage: %s <input_file> <key.bin> <iv.bin> <output_file>\n", argv[0]);
        exit(1);
    }

    size_t data_len, key_len, iv_len;
    unsigned char *data = read_file(argv[1], &data_len);
    unsigned char *key = read_file(argv[2], &key_len);
    unsigned char *iv = read_file(argv[3], &iv_len);

    if (key_len != 16 || iv_len != 16) {
        fprintf(stderr, "Key and IV must be 16 bytes.\n");
        exit(1);
    }

    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    unsigned char *out = malloc(data_len);
    int out_len, tmp_len;

    if (!EVP_DecryptInit_ex(ctx, EVP_sm4_cbc(), NULL, key, iv) ||
        !EVP_DecryptUpdate(ctx, out, &out_len, data, data_len) ||
        !EVP_DecryptFinal_ex(ctx, out + out_len, &tmp_len)) {
        fprintf(stderr, "SM4 decryption failed.\n");
        exit(1);
    }
    out_len += tmp_len;

    write_file(argv[4], out, out_len);
    printf("SM4 decryption succeeded.\n");

    free(data); free(key); free(iv); free(out);
    EVP_CIPHER_CTX_free(ctx);
    return 0;
}
